package com.hotec.PROJECT_NAME.utils;

import cn.hutool.core.io.FileUtil;
import com.hotec.PROJECT_NAME.component.exception.exc.BizException;
import cn.hutool.core.lang.Assert;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.Objects;

public class UtilsFile extends FileUtil {
    /**
     * 获取classpath中的文件
     * @param path 文件名/文件路径
     * @param extName 文件后缀
     * @return File
     */
    public static File getFileInClassPath (String path, String extName){
        Assert.notBlank(path, "请传入路径或文件名！");

        path = path.replaceAll("classpath:", "");

        try {
            InputStream inputStream = FileUtil.class.getClassLoader().getResourceAsStream(path);

            File tempFile = File.createTempFile(path, extName);

            if (Objects.isNull(inputStream)) {
                inputStream = new FileInputStream(getWebRootPath(path));
            }

            writeFromStream(inputStream, tempFile);

            inputStream.close();

            return tempFile;
        } catch (IOException e) {
            UtilsLog.log(UtilsFile.class, e);

            throw new BizException("文件创建异常！");
        }
    }

    /**
     * 获取classpath中的文件
     * @param path 文件名/文件路径
     * @return File
     */
    public static File getFileInClassPath (String path){
        return getFileInClassPath(path, extName(path));
    }

    public static String getWebRootPath(String filePath) {
        try {
            String path = Objects.requireNonNull(FileUtil.class.getClassLoader().getResource("")).toURI().getPath();
            path = path.replace("WEB-INF/classes/", "");
            path = path.replace("file:/", "");
            return path + filePath;
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }
}
